package com.qhy.springcloud.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Date;

/**
 * @author qiuhongyu
 * @date 2020/11/12 11:37
 */
@Component
public class MyLogGateWayFilter implements GlobalFilter, Ordered {
    private Logger logger = LoggerFactory.getLogger(MyLogGateWayFilter.class);
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        logger.info("**********come in MyLogGateWayFilter:" + new Date());
        // 获取请求参数
        String username = exchange.getRequest().getQueryParams().getFirst("username");
        if (username == null) {
//            logger.info("**********用户名为null,非法用户！");
            //给用户响应内容
            exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
            return exchange.getResponse().setComplete();
        }
        //把这次判断通过的续传下去，后面的过滤器会继续判验证
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        //过滤器执行的顺序，越小越先执行(如：还有一个过滤器设置为1，那么0过滤器执行后1才执行
        return 0;
    }
}
